package com.gitee.wsl.io.api

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.cbor.Cbor
import kotlinx.serialization.json.Json.Default.encodeToString

interface ValueWriter {
    fun <T:Any> put(key: String,value:T)

    fun putInt(key: String, value: Int) = put(key,value)

    fun putFloat(key: String, value: Float) = put(key,value)

    fun putLong(key: String, value: Long) = put(key,value)

    fun putDouble(key: String, value: Double) = put(key,value)

    fun putBoolean(key: String, value: Boolean) = put(key,value)

    fun putString(key: String, value: String) = put(key,value)

    fun putByteArray(key: String,value:ByteArray) = put(key,value)

    fun remove(key: String)

}

inline fun <reified T:Any> ValueWriter.putEncoded(key:String, value:T){
    putString(key,encodeToString(value))
}

inline fun <reified T> ValueWriter.putEncoded(name: String, value: T, serializer: SerializationStrategy<T>)
        = putString(name, encodeToString(serializer,value))

@OptIn(ExperimentalSerializationApi::class)
fun <T> ValueWriter.putEncodedUseByteArray(
    key: String,
    value: T,
    serializer: SerializationStrategy<T>,
) {
    return try {
        putByteArray(key, Cbor.encodeToByteArray(serializer, value))
    } catch (e: Exception) {
       //
    }
}




